import jwt,json
from flask import current_app

def generate_token(payload,expiry,algorithm='HS256'):
    """生成token"""
    key = current_app.config.get('SERCRET_KEY')
    if 'exp' not in payload:
        payload['exp'] = expiry
    try:
        token = jwt.encode(payload,key,algorithm)
        return token
    except Exception as e:
        print('generate_token error',e)
        return e

def check_token(token):
    """校验token"""
    key = current_app.config.get('SERCRET_KEY')
    payload = jwt.decode(token,key,algorithms=['HS256'])
    return payload


from datetime import datetime,timedelta
def _generate_token(payload,is_refresh=True):
    #设置有效期,第一次默认生成2个小时的有效期
    expiry = datetime.now() + timedelta(seconds=30)
    token = "JWT " + generate_token(payload,expiry)
    #默认需要刷新生成token
    if is_refresh:
        # 刷新生成的token，有效期15天
        expiry = datetime.now() + timedelta(days=15)
        #给paload添加刷新token的标识
        payload.update({'is_refresh':True})
        print("p",payload)
        refresh_token = "JWT " + generate_token(payload,expiry)
    else:
        refresh_token = None
    return token,refresh_token

